load('application');

before(loadGroup, {only: ['show', 'edit', 'update', 'destroy']});

action('new', function () {
    this.title = 'New group';
    this.group = new Group;
    render();
});

action(function create() {
    Group.create(req.body.Group, function (err, group) {
        if (err) {
            flash('error', 'Group can not be created');
            render('new', {
                group: group,
                title: 'New group'
            });
        } else {
            flash('info', 'Group created');
            redirect(path_to.groups());
        }
    });
});

action(function index() {
    this.title = 'Groups index';
    Group.all(function (err, groups) {
        render({
            groups: groups
        });
    });
});

action(function show() {
    this.title = 'Group show';
    render();
});

action(function edit() {
    this.title = 'Group edit';
    render();
});

action(function update() {
    this.group.updateAttributes(body.Group, function (err) {
        if (!err) {
            flash('info', 'Group updated');
            redirect(path_to.Group(this.Group));
        } else {
            flash('error', 'Group can not be updated');
            this.title = 'Edit group details';
            render('edit');
        }
    }.bind(this));
});

action(function destroy() {
    this.group.destroy(function (error) {
        if (error) {
            flash('error', 'Can not destroy group');
        } else {
            flash('info', 'Group successfully removed');
        }
        send("'" + path_to.groups() + "'");
    });
});

function loadGroup() {
    Group.find(params.id, function (err, group) {
        if (err || !group) {
            redirect(path_to.groups());
        } else {
            this.group = group;
            next();
        }
    }.bind(this));
}
